package com.cheer.ba.view.base;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.bigkoo.svprogresshud.SVProgressHUD;
import com.cheer.ba.service.NetBroadCastReciver;
import com.cheer.ba.utils.NetUtil;
import com.cheer.ba.utils.StringUtils;
import com.cheer.slidingmenu.app.SlidingFragmentActivity;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.cheer.ba.R;
import com.cheer.ba.app.AppManager;
import com.cheer.ba.cache.preference.Session;
import com.cheer.ba.constant.IntentCode;
import com.cheer.ba.event.BaseEvent;
import com.cheer.ba.presenter.IPresenter;
import com.cheer.ba.utils.NetUtils;
import com.cheer.ba.view.activity.LoginAty;
import com.cheer.ba.view.dialog.DialogUtils;
import com.cheer.ba.widget.callback.I_SkipActivity;
import com.cheer.ba.widget.swipeback.SwipeBackLayout;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * activity 的基类
 */
public abstract class BaseAty extends AppCompatActivity implements IViewController, I_SkipActivity, NetBroadCastReciver.NetEvent {

    //整体布局-根布局
    @BindView(R.id.id_base_root)
    public LinearLayout mRootViewLL;
    //头部标题栏-根布局
    @BindView(R.id.id_base_top_title)
    RelativeLayout mTitlebarViewLL;
    //返回按钮
    @BindView(R.id.id_titlebar_back_txt)
    public TextView mTitleBarBackTxt;
    //登录按钮
    @BindView(R.id.id_titlebar_login_img)
    ImageView mLoginImg;
    //扫描按钮
    @BindView(R.id.id_titlebar_scan_img)
    ImageView mScanImg;
    //输入框
    @BindView(R.id.id_search_key_edit)
    EditText mEditSearchKey;
    //标题-文字
    @BindView(R.id.id_titlebar_title_txt)
    TextView mTitleTxt;
    //标题-图片
    @BindView(R.id.id_titlebar_middle_icon_img)
    ImageView mTitleImg;
    //右侧按钮-文字
    @BindView(R.id.id_titlebar_right_txt)
    public TextView mRightTxt;
    //右侧按钮-图标
    @BindView(R.id.id_titlebar_right_icon_img)
    RelativeLayout mRightIconImg;
    //img
    @BindView(R.id.id_right_img)
    ImageView mRightImg;
    //右侧按钮-图标-红点
    @BindView(R.id.id_titlebar_right_icon_dot_img)
    ImageView mRightDotImg;

    public String TAG;
    protected IPresenter presenter;
    protected SwipeBackLayout layout;
    public Activity aty;
    private Dialog dialog;

    private FrameLayout mFrameContent;

    private int netMobile;

    private NetBroadCastReciver.NetEvent mNetEvent;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.aty = this;
        TAG = getClass().getSimpleName();
        Log.d(TAG, "onCreate");
//        AppManager.add(this);
        setContentView(R.layout.aty_base);
        mFrameContent = (FrameLayout) findViewById(R.id.id_base_content_ll);
        View view = loadView(getLayoutInflater());
        if (view == null) {
            view = loadView(getLayoutInflater(), null);
        }
        if (view != null) {
            if (mFrameContent != null) {
                mFrameContent.addView(view);
            }
        }
        ButterKnife.bind(this);
        initTint();
        initTitleBar();
        initSwipeBack();
        initPresenter();
        if (presenter != null) {
            presenter.attachView(this);
        }
        mNetEvent = this;
        inspectNet();
        initView();
        initData();
        mFrameContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                hideSoft(mFrameContent);
            }
        });
    }

    /**
     * 初始化时判断有没有网络
     *
     * @return
     */
    public boolean inspectNet() {
        this.netMobile = NetUtil.getNetWorkState(this);
        return isNetConnect();
    }

    /**
     * 网络变化之后的类型
     */
    @Override
    public void onNetChange(int netMobile) {
        this.netMobile = netMobile;
        isNetConnect();
    }

    /**
     * 判断有误网络
     *
     * @return true 有 ，false 没有
     */
    public boolean isNetConnect() {
        if (netMobile == 1) {
            return true;
        } else if (netMobile == 0) {
            return true;
        } else if (netMobile == -1) {
            return false;
        }
        return false;
    }

    @Nullable
    @Override
    public View loadView(LayoutInflater inflater) {
        return null;
    }

    @Nullable
    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return null;
    }

    /**
     * 设置状态栏颜色，沉浸式状态栏
     */
    private void initTint() {
        if (isStatusBarTint()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                SystemBarTintManager tintManager = new SystemBarTintManager(this);
                tintManager.setStatusBarTintEnabled(true);
                tintManager.setStatusBarTintResource(getStatusTintColor());
            }
        }
    }

    /**
     * 初始化标题栏
     * 判断是否显示TitleBar
     */
    private void initTitleBar() {
        if (isTitleBarShow()) {
            mTitlebarViewLL.setVisibility(View.VISIBLE);
            if (isSupportBack()) {
                mTitleBarBackTxt.setVisibility(View.VISIBLE);
                mTitleBarBackTxt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setResult(IntentCode.General.ATY_FINISH);
                        finish();
                    }
                });
            } else {
                mTitleBarBackTxt.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(getTitle())) {
                setTitleText(getTitle().toString());
            }
        } else {
            mTitlebarViewLL.setVisibility(View.GONE);
        }
    }

    /**
     * 展示左侧图标
     */
    public void showLeftIcon(int drawable, View.OnClickListener listener) {
        mTitleBarBackTxt.setVisibility(View.GONE);
        mLoginImg.setVisibility(View.VISIBLE);
        mLoginImg.setImageResource(drawable);
        if (null != listener) {
            mLoginImg.setClickable(true);
            mLoginImg.setOnClickListener(listener);
        } else {
            mLoginImg.setClickable(false);
        }
    }

    /**
     * 设置TitleBar中间标题，不处理点击事件
     *
     * @param text
     */
    protected void setTitleText(String text) {
        setTitleText(text, null);
    }

    /**
     * 设置TitleBar中间标题，处理点击事件
     *
     * @param text
     */
    protected void setTitleText(String text, View.OnClickListener listener) {
        mTitleTxt.setVisibility(View.VISIBLE);
        mTitleTxt.setText(text);
        if (listener != null) {
            mTitleTxt.setClickable(true);
            mTitleTxt.setOnClickListener(listener);
        } else {
            mTitleTxt.setClickable(false);
        }
    }

    /**
     * 处理搜索框
     */
    public EditText setSearchTxt(String mkey, View.OnClickListener listener) {
        mEditSearchKey.setVisibility(View.VISIBLE);
        if (!StringUtils.isEmpty(mkey)) {
            mEditSearchKey.setText(mkey);
        }
        if (null != listener) {
            mEditSearchKey.setClickable(true);
            mEditSearchKey.setOnClickListener(listener);
        } else {
            mEditSearchKey.setClickable(false);
        }
        return mEditSearchKey;
    }

    /**
     * 初始化滑动返回
     */
    private void initSwipeBack() {
        if (isSupportSwipeback()) {
            setShowFinishLayout();
        }
    }

    /**
     * 向左滑动finish掉activity
     */
    public void setShowFinishLayout() {
        layout = (SwipeBackLayout) LayoutInflater.from(this).inflate(
                R.layout.base, null);
        layout.attachToActivity(this);
    }

    @Override
    public void initPresenter() {
        Log.d(TAG, "initPresenter");
    }


    protected void hideTitleBar() {
        mTitleTxt.setVisibility(View.GONE);
    }

    @Override
    public boolean hasDataInPage() {
        return false;
    }

    /**
     * 设置TitleBar左侧返回文字
     *
     * @param text
     */
    protected void setBackText(String text) {
        if (isTitleBarShow() && isSupportBack()) {
            mTitleBarBackTxt.setText(text);
        }
    }

    /**
     * 设置TitleBar左侧返回文字，去掉图标
     *
     * @param text
     */
    protected void setBackTextWithNull(String text) {
        if (isTitleBarShow() && isSupportBack()) {
            mTitleBarBackTxt.setText(text);
            mTitleBarBackTxt.setCompoundDrawables(null, null, null, null);
        }
    }

    /**
     * 用户是否登录
     *
     * @param isShowDialog 是否显示弹出框 true 显示
     * @return
     */
    public boolean isLogin(boolean isShowDialog) {
        if (Session.getUserIsLogin()) {
            return true;
        } else {
            if (isShowDialog) {
                showLoginDialog();
            } else {
                Intent login = new Intent(aty, LoginAty.class);
                startActivityForResult(login, IntentCode.Login.LOGIN_REQUEST_CODE);
            }
            return false;
        }
    }

    /**
     * 弹出登录提示框
     */
    public void showLoginDialog() {
        if (isFinishing()) {
            return;
        }
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        View view = getLayoutInflater().inflate(R.layout.login_remind, null, false);
        TextView mTvTitle = (TextView) view.findViewById(R.id.id_remind_login_txt);
        mTvTitle.setText(getString(R.string.login_remind));
        mTvTitle.setSingleLine(false);
        TextView mTxtCancel = (TextView) view.findViewById(R.id.id_login_cancel_txt);
        mTxtCancel.setText(getString(R.string.login_look_again));
        mTxtCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        TextView mTxtConfirm = (TextView) view.findViewById(R.id.id_login_confirm_txt);
        mTxtConfirm.setText(getString(R.string.login_with_space));
        mTxtConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Intent login = new Intent(aty, LoginAty.class);
                startActivityForResult(login, IntentCode.Login.LOGIN_REQUEST_CODE);
            }
        });

        dialog = DialogUtils.selfDialog(this, view, true);
        dialog.show();
    }

    /**
     * 是否有网络
     *
     * @return
     */
    public boolean isNetWork() {
        if (NetUtils.isNetworkConnected(aty)) {
            return true;
        } else {
            if (!isFinishing()) {
                SVProgressHUD.showInfoWithStatus(aty, getString(R.string.no_net_work));
            }
            return false;
        }
    }

    /**
     * 设置标题栏右侧文字，不处理点击事件
     * 设置右侧文字后，右侧图标将不显示
     *
     * @param text
     */
    protected void setTitleRight(String text) {
        setTitleRight(text, null);
    }

    /**
     * 设置标题栏右侧文字，处理点击事件
     * 设置右侧文字后，右侧图标将不显示
     *
     * @param text
     */
    public TextView setTitleRight(String text, View.OnClickListener listener) {
        mRightIconImg.setVisibility(View.GONE);
        mRightDotImg.setVisibility(View.GONE);
        mRightTxt.setVisibility(View.VISIBLE);
        mRightTxt.setText(text);
        if (listener != null) {
            mRightTxt.setClickable(true);
            mRightTxt.setOnClickListener(listener);
        } else {
            mRightTxt.setClickable(false);
        }
        return mRightTxt;
    }

    /**
     * 设置右侧图标，处理点击事件
     * 设置右侧图标后，右侧文字将不显示
     *
     * @param hasNew   是否显示消息红点
     * @param listener
     */
    protected ImageView setTitleIcon(int resId, boolean hasNew, View.OnClickListener listener) {
        if (hasNew) {
            mRightDotImg.setVisibility(View.VISIBLE);
        } else {
            mRightDotImg.setVisibility(View.GONE);
        }
        mRightTxt.setVisibility(View.GONE);
        mRightIconImg.setVisibility(View.VISIBLE);
        mRightImg.setImageResource(resId);
        if (listener != null) {
            mRightIconImg.setClickable(true);
            mRightIconImg.setOnClickListener(listener);
        }
        return mRightImg;
    }

    /**
     * 清除右侧图标和文字
     */
    public void clearRightIcon() {
        mRightTxt.setVisibility(View.GONE);
        mRightIconImg.setVisibility(View.GONE);
        mLoginImg.setVisibility(View.GONE);
    }

    /**
     * 清除右侧图标上的小红点
     */
    protected void clearTitleIconDot() {
        mRightDotImg.setVisibility(View.GONE);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
//        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
//        MobclickAgent.onPause(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
        AppManager.remove(this);
        if (presenter != null) {
            presenter.detachView();
        }
//        RefWatcher refWatcher = App.getRefWatcher(this);
//        refWatcher.watch(this);
    }

    /**
     * @return 状态栏颜色
     */
    protected int getStatusTintColor() {
        if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
            return R.color.colorPrimaryDark;
        } else if (Build.VERSION.SDK_INT >= 21 && Build.VERSION.SDK_INT < 23) {
            return R.color.colorPrimaryDark;
        } else {
            return R.color.colorPrimaryDark;
        }
    }

    /**
     * 指定Activity跳转，不带参数
     *
     * @param claz 组件名
     */
    protected void jump(Class<? extends Activity> claz) {
        jump(claz, null);
    }

    /**
     * 指定Activity跳转，带参数
     *
     * @param claz 组件名
     * @param data 参数
     */
    protected void jump(Class<? extends Activity> claz, Bundle data) {
        Intent intent = new Intent(this, claz);
        if (data != null) {
            intent.putExtras(data);
        }
        startActivity(intent);
    }

    /**
     * skip to @param(cls)，and call @param(aty's) finish() method
     */
    @Override
    public void skipActivity(Activity aty, Class<?> cls) {
        showActivity(aty, cls);
        aty.finish();
    }

    /**
     * skip to @param(cls)，and call @param(aty's) finish() method
     */
    @Override
    public void skipActivity(Activity aty, Intent it) {
        showActivity(aty, it);
        aty.finish();
    }

    /**
     * skip to @param(cls)，and call @param(aty's) finish() method
     */
    @Override
    public void skipActivity(Activity aty, Class<?> cls, Bundle extras) {
        showActivity(aty, cls, extras);
        aty.finish();
    }

    /**
     * show to @param(cls)，but can't finish activity
     */
    @Override
    public void showActivity(Activity aty, Class<?> cls) {
        Intent intent = new Intent();
        intent.setClass(aty, cls);
        aty.startActivity(intent);
    }

    /**
     * show to @param(cls)，but can't finish activity
     */
    @Override
    public void showActivity(Activity aty, Intent it) {
        aty.startActivity(it);
    }

    /**
     * show to @param(cls)，but can't finish activity
     */
    @Override
    public void showActivity(Activity aty, Class<?> cls, Bundle extras) {
        Intent intent = new Intent();
        intent.putExtras(extras);
        intent.setClass(aty, cls);
        aty.startActivity(intent);
    }

    /**
     * 弹出框消失
     */
    public void SVProgressHUDDismiss() {
        if (SVProgressHUD.isShowing(this)) {
            SVProgressHUD.dismiss(this);
        }
    }

    /**
     * 是否使用沉浸式状态栏
     *
     * @return true 使用,false 不使用
     */
    protected boolean isStatusBarTint() {
        return true;
    }

    /**
     * 是否显示标题栏
     *
     * @return true 显示，false 隐藏
     */
    protected boolean isTitleBarShow() {
        return true;
    }

    /**
     * 若标题栏已显示，是否显示标题栏"<返回"
     *
     * @return true 支持返回按钮返回，false 不显示返回
     */
    protected boolean isSupportBack() {
        return true;
    }

    /**
     * 是否支持滑动返回
     *
     * @return true 允许滑动返回，false 不允许滑动返回
     */
    protected boolean isSupportSwipeback() {
        return true;
    }


    @Override
    public <T> void updateView(T t) {
        Log.d(TAG, "updateViewWithLoadMore");
    }

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
    }

    @Override
    public <T> void updateViewWithLoadMore(T t, boolean loadMore, String tag) {
    }

    @Override
    public <T> void updateViewWithLoadMore(T t, int flag, String str, boolean loadMore, boolean direction, int size) {
    }

    @Override
    public void onLoadingStatus(IViewController mView, boolean isHandler, int loadingStatus, int flag) {
    }

    @Override
    public void onLoadingStatus(IViewController mView, boolean isHandler, int loadingStatus, int flag, String string) {
    }

    @Override
    public void onLoadingStatus(IViewController mView, boolean isHandler, int loadingStatus, int flag, String string, boolean loadMore) {
    }

    @Override
    public void onLoadingStatus(IViewController mView, boolean isHandler, int loadingStatus, int flag, String string, boolean loadMore, boolean isDirection) {
    }

    @Override
    public void showLoading() {
        Log.d(TAG, "showLoading");
    }

    @Override
    public void hideLoading() {
        Log.d(TAG, "hideLoading");
    }

    @Override
    public void initView() {
    }

    @Override
    public void initData() {
    }

    @Override
    public void handlerByPage(int flag1, int flag2) {
    }

    @Override
    public void handlerByPage(int flag1, int flag2, String string) {
    }

    @Override
    public void handlerByPage(int flag1, int flag2, boolean loadMore) {
    }

    @Override
    public void handlerByPage(int flag1, int flag2, boolean loadMore, boolean direction) {
    }

    //    /**
//     * EventBus 事件处理
//     *
//     * @param event
//     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(BaseEvent event) {
    }

    /**
     * 隐藏软键盘
     *
     * @param mRootView
     */
    public void hideSoft(final View mRootView) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                imm.hideSoftInputFromWindow(mRootView.getWindowToken(), 0);
            }
        }, 10);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 进入系统设置界面
     */
    protected void requestPermission(int requestCode) {
        // TODO Auto-generated method stub
        // 6.0以上系统才可以判断权限

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
            // 进入设置系统应用权限界面
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            startActivity(intent);
            return;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
            // 进入设置系统应用权限界面
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            startActivity(intent);
            return;
        }
        return;
    }

    //设置上次刷新的时间
    //mRefresh.restoreLastRefreshTime(lastRefreshTime);
    //XRefreshView不仅支持手势下拉刷新，也支持按钮点击开始刷新，
    //mRefresh.startRefresh();

    /**
     * @param mRefresh       刷新控件
     * @param isUpRefresh    是否可以上拉刷新
     * @param isLoadMore     是否加载更多
     * @param isAutoRefresh  是否可以自动刷新
     * @param isAutoLoadMore 是否滑动到底部自动加载更多
     */
    public void setXRefreshView(XRefreshView mRefresh, boolean isUpRefresh, boolean isLoadMore, boolean isAutoRefresh, boolean isAutoLoadMore, View mHeadView, View mFootView) {
        // 设置是否可以上拉刷新
        mRefresh.setPullLoadEnable(isUpRefresh);
        //是否加载更多
        mRefresh.setPullLoadEnable(isLoadMore);
        //设置是否可以自动刷新
        mRefresh.setAutoRefresh(isAutoRefresh);
        //滑动到底部自动加载更多,目前只做了Abslistview和Recylerview的,true会自动加载更多.
        // false则相反。传入false的话，如果是listview，需要上拉才能加载更多，如果是Recylerview，则会需要点击才能加载更多。就像这样
        mRefresh.setAutoLoadMore(isAutoLoadMore);

        //如果需要在手指横向移动的时候，让XRefreshView不拦截事件
        mRefresh.setMoveForHorizontal(true);
        //设置当下拉刷新完成以后，headerview和footerview被固定的时间
        //注:考虑到ui效果，只有时间大于1s的时候，footerview被固定的效果才会生效
        mRefresh.setPinnedTime(1000);
        //刷新时，不让里面的列表上下滑动
        mRefresh.setPinnedContent(false);
        if (null != mHeadView) {
            mRefresh.setCustomHeaderView(mHeadView);
        }
        if (null != mFootView) {
            mRefresh.setCustomFooterView(mFootView);
        }
    }

    /**
     * 停止下拉刷新
     *
     * @param mRefresh
     * @param time
     */
    public void stopRefresh(final XRefreshView mRefresh, int time) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefresh.stopRefresh();
            }
        }, time);
    }

    /**
     * 停止加载更多
     *
     * @param mRefresh
     * @param time
     */
    public void stopLoadMore(final XRefreshView mRefresh, int time) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefresh.stopLoadMore();
            }
        }, time);
    }

    /**
     * 停止加载更多
     *
     * @param mRefresh
     * @param time
     */
    public void stopLoadComplete(final XRefreshView mRefresh, int time) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefresh.setLoadComplete(true);
            }
        }, time);
    }
}
